/*
 * Copyright (c) 2008, 2016, OneAPM and/or its affiliates. All rights reserved.
 */
package me.yufan.chess.utils;

import me.yufan.chess.Main;
import org.newdawn.slick.util.Log;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.jar.JarFile;

/**
 * Title: Utils
 * Description: 程序基础工具类, 封装绝大多数辅助操作.
 *
 * @author Yufan
 * @version 1.0.0
 * @since 2016-01-26 19:13
 */
public final class Utils {

    private Utils() {
        // No Construct
    }

    /**
     * Returns whether or not the application is running within a JAR.
     *
     * @return true if JAR, false if file
     */
    public static boolean isJarRunning() {
        return Main.class.getResource(String.format("%s.class", Main.class.getSimpleName()))
            .toString().startsWith("jar:");
    }

    /**
     * Returns the JarFile for the application.
     *
     * @return the JAR file, or null if it could not be determined
     */
    public static JarFile getJarFile() {
        try {
            if (isJarRunning()) {
                return new JarFile(new File(
                    Main.class.getProtectionDomain().getCodeSource().getLocation().toURI()), false);
            }
        } catch (URISyntaxException | IOException e) {
            Log.error("Could not determine the JAR file.", e);
        }
        return null;
    }
}
